const express = require("express");
const router = express.Router(); // 创建服务器的实例对象
const multer = require("multer");
const upload = multer({ dest: "images/uploads/" }); // 创建上传实例对象
let fs = require("fs");
let path = require("path");
const goods_handler = require("../router_handler/goods"); // 导入处理函数模块

router.get("/goodslist", goods_handler.getGoodsList); // 获取所有商品

// 获取上传图片
router.post("/upload", upload.single("file"), (req, res) => {
  fs.readFile(req.file.path, (err, data) => {
    if (err) return res.send("上传失败");
    // 设置不会重复的名字
    let time =
      Date.now() + (Math.random() * 999 + parseInt(Math.random() * 2222));
    // 拿取后缀名
    let extname = req.file.mimetype.split("/")[1];
    // 合并名字
    let keepname = time + "." + extname;
    fs.writeFile(
      path.join(__dirname, "../images/uploads/" + keepname),
      data,
      (err) => {
        if (err) return res.send("写入失败" + err);
        fs.unlinkSync(req.file.path);
        res.send({
          code: 200,
          message: "上传成功",
          src: "http://192.168.27.59/imgs/uploads/" + keepname,
        });
      }
    );
  });
});

// // 上传图片处理函数
// var storage = multer.diskStorage({
//   destination: function (req, file, cb) {
//     cb(null, `../lamp_API/images/uploads`);
//   },
//   filename: function (req, file, cb) {
//     // 设置不会重复的名字
//     let time =
//       Date.now() + (Math.random() * 999 + parseInt(Math.random() * 2222));
//     // 拿取后缀名
//     let extname = file.mimetype.split("/")[1];
//     // 合并名字
//     let keepname = time + "." + extname;
//     cb(null, keepname);
//   },
// });
// var upload = multer({ storage });
// // 上传图片处理接口
// router.post("/upload", upload.array("files", 20), (req, res) => {
//   let imgObj = [];
//   req.files.forEach((item) => {
//     let str = `http://192.168.27.59/img/${item.filename}`;
//     imgObj.push(str);
//   });
//   res.send({ code: 200, data: imgObj });
// });

router.post("/addgoods", goods_handler.addGoods); // 添加商品

router.post("/alterGoods", goods_handler.alterGoods); // 修改商品状态

module.exports = router;
